/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ui.helpers;

import core.Database;
import core.XmlGenerator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import ui.ApplicationWindow;
import org.apache.log4j.Logger;
import ui.DbVersioning;

/**
 *
 * @author Sakis Vtdk <sakis.vtdk@gmail.com>
 */
public class SaveListener implements ActionListener
{

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		//get the file chooser
		JFileChooser fileChooser = ApplicationWindow.getApplicationWindow().getFileChooser();
		//set the filter
		fileChooser.setCurrentDirectory(new File(DbVersioning.DEFAULT_DATA_FOLDER));
		FileFilter filter = new FileNameExtensionFilter("Database Versioning files", DbVersioning.FILE_EXTENSION);
		fileChooser.setFileFilter(filter);

		//set the default location
		fileChooser.setCurrentDirectory(new File(DbVersioning.DEFAULT_DATA_FOLDER));

		//get the user's choice
		int choice = fileChooser.showSaveDialog(null);
		
		if(choice == JFileChooser.APPROVE_OPTION)
		{
			File file = fileChooser.getSelectedFile();

			//get the name of the file
			String fileName = file.getName();

			//get only the path of the file, without the name
			String path = file.getPath().substring(0, file.getPath().indexOf(fileName));

			//if the name given does not contain the extension, we add it
			if(!ApplicationWindow.getApplicationWindow().fileHasExtension(file, DbVersioning.FILE_EXTENSION))
			{
				fileName += "."+ DbVersioning.FILE_EXTENSION;
				file = new File(path + fileName);
			}

			//get a snapshot of the database first
			Database.takeSnapshot();

			//and then try to save the file
			try
			{
				ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
				outputStream.writeObject(Database.getDatabase());

				outputStream.close();

				//save the xml file containing the changes
				saveXml();
			}
			catch(IOException exc)
			{
				JOptionPane.showMessageDialog(null, "There was an error when saving to file", "Error", JOptionPane.ERROR_MESSAGE);
				log.fatal("The following error occured when trying to save the file: "+ exc.getMessage());
			}
		}
	}

	private void saveXml()
	{
		//get an XML generator object
		XmlGenerator xmlGenerator = XmlGenerator.getXmlGenerator();

		//build and save the xml file
		xmlGenerator.buildXml(DbVersioning.DEFAULT_CHANGES_FOLDER + File.separator);
	}

	
	
	private static Logger log = Logger.getLogger(SaveListener.class);
	
}
